package cn.hx.admin.util;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzSchedulerUtils {

    private Scheduler scheduler;

    public QuartzSchedulerUtils() {
        try {
            // 创建调度器
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            // 开启调度器
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public void addJob(String jobName, String groupName, Class<? extends Job> jobClass, String cronExpression) {
        try {
            // 创建任务
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity(jobName, groupName)
                    .build();

            // 创建触发器
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobName + "Trigger", groupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                    .build();

            // 将任务和触发器加入调度器
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public void updateJob(String jobName, String groupName, String cronExpression) {
        try {
            TriggerKey triggerKey = new TriggerKey(jobName + "Trigger", groupName);
            CronTrigger newTrigger = (CronTrigger) TriggerBuilder.newTrigger()
                    .withIdentity(triggerKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                    .build();
            scheduler.rescheduleJob(triggerKey, newTrigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public void deleteJob(String jobName, String groupName) {
        try {
            JobKey jobKey = new JobKey(jobName, groupName);
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public void shutdown() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
